import util from '../../utils/util.js';

/** 
*字符串转json 
*/
function jsonToString(data) {
  return JSON.stringify(data);
}

function sendData(obj) {
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    mask: true
  })
  var listBody = "";
  for (var i = 0; i < obj.data.list.length; i++) {
    if (i > 0)
      listBody = listBody + "," + JSON.stringify(obj.data.list[i]);
    else
      listBody = JSON.stringify(obj.data.list[i]);
  }
  listBody = "[" + listBody + "]";
  // console.log(listBody);

  wx.request({
    url: getApp().globalData.url + '/PLanAndTask/addPlanWithTask',
    data: util.json2Form({ "key": listBody, "userId": wx.getStorageSync("userId") }),
    method: 'POST',
    header: {
      // 'Content-Type': 'application/json'
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      wx.hideToast();
      doHttp(obj);

    }
  })
}

function doHttp(obj) {
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    mask: true
  })
  wx.request({
    url: getApp().globalData.url + '/PLanAndTask/getPlanAndTask',
    data: {
      id: wx.getStorageSync("userId")
    },
    method: 'POST',
    header: {
      // 'Content-Type': 'application/json'
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      wx.hideToast();
      //   listName: '默认计划',
      //   item: [{
      //     itemName: 'a-1',
      //     content: '1-1中的内容',
      //     time: '2015-05-06',
      //     isChecked: false
      var listTemp = new Array();
      for (var key in res.data) {
        var itemTemp = new Array();
        for (var y = 0; y < res.data[key].length; y++) {
          itemTemp = [{
            itemId: res.data[key][y].task_id,
            itemName: res.data[key][y].task_title,
            content: "",
            time: "",
            isChecked: false
          }].concat(itemTemp);
        }
        var isShow = false;
        console.log(obj.data.list.length - key);
        if (cuSelectNum == obj.data.list.length - key) {
          isShow = true;
        } else {
          isShow = false;
        }

        listTemp = [{
          show: isShow,
          listId: res.data[key][0].plan_id,
          listName: res.data[key][0].plan_title,
          count: "0/0",
          item: itemTemp
        }].concat(listTemp);
      }
      wx.setStorageSync("list", obj.data.list);
      obj.setData({
        list: listTemp
      })

      //zzp_1
      setTitle(obj);
      setListItemCount(obj);

      // // console.log('触发了最外层');
      // let Index = cuSelectNum, //获取点击的下标值 
      //   list = obj.data.list;
      // list[Index].show = !list[Index].show || false; //变换其打开、关闭的状态
      // if (list[Index].show) { //如果点击后是展开状态，则让其他已经展开的列表变为收起状态 
      //   obj.packUp(list, Index);
      // }
      // list[cuSelectNum].show = true;
      // cuSelectNum = Index;

      // obj.setData({
      //   buttonText: list[Index].listName,
      //   list
      // });
    },
    fail: function (e) {
      wx.hideToast();
      console.log("服务器连接失败");
    }
  })
}
/**用户选择的第几个计划 */
var cuSelectNum = 0;

function setTitle(_this) {
  var count = 0;
  var countChecked = 0;

  for (var x = 0; x < _this.data.list.length; x++) {
    for (var y = 0; y < _this.data.list[x].item.length; y++) {
      if (_this.data.list[x].item[y].isChecked) {
        countChecked++;
      }
      count++;
    }
  }

  wx.setNavigationBarTitle({
    title: "任务 " + countChecked + "/" + count
  })
}

function setListItemCount(_this) {
  for (var x = 0; x < _this.data.list.length; x++) {
    var count = 0;
    var countChecked = 0;
    for (var y = 0; y < _this.data.list[x].item.length; y++) {
      if (_this.data.list[x].item[y].isChecked) {
        countChecked++;
      }
      count++;
    }

    _this.data.list[x].count = countChecked + "/" + count;
  }


  _this.setData({
    list: _this.data.list
  })
}

function showBottomInput(_this) {
  // 显示遮罩层
  var animation = wx.createAnimation({
    duration: 300,
    timingFunction: "ease-in-out",
    delay: 0
  })
  _this.animation = animation
  animation.translateY(100).step()
  _this.setData({
    animationData: animation.export(),
    showModalStatus: true,
    isBlur: true,
    isPlayScale: "animation: scaleMoveIn 0.1s linear;animation-fill-mode: forwards;"
  })
  setTimeout(function () {
    animation.translateY(0).step()
    _this.setData({
      animationData: animation.export()
    })
  }.bind(_this), 0)
}

function hideBottomInput(_this) {
  // 隐藏遮罩层
  var animation = wx.createAnimation({
    duration: 300,
    timingFunction: "ease-in-out",
    delay: 0
  })
  _this.animation = animation
  animation.translateY(100).step()
  _this.setData({
    animationData: animation.export(),
    isBlur: false,
    isPlayScale: "animation: scaleMoveOut 0.1s linear;animation-fill-mode: forwards;"
  })
  setTimeout(function () {
    animation.translateY(0).step()
    _this.setData({
      animationData: animation.export(),
      showModalStatus: false,
    })
  }.bind(_this), 0)
}

function playTextAnim(_this) {
  // //创建节点选择器
  // var query = wx.createSelectorQuery();
  // query.select('#ssss').boundingClientRect()
  // query.exec(function (res) {
  //   //res就是 所有标签为mjltest的元素的信息 的数组
  //   console.log(res);
  //   //取高度
  //   console.log(res[0].y);
  // })

  // /**
  //  * 动画
  //  */
  // var animation = wx.createAnimation({
  //   transformOrigin: "50% 50%",
  //   duration: 1000,
  //   timingFunction: "ease",
  //   delay: 0
  // })
  // _this.animation = animation;
  // animation.translateY(-300).step();
  // _this.setData({
  //   transform: animation.export(),
  // })
}

Page({

  /** * 页面的初始数据 */
  actioncnt: function () {
    var itemListTemp = new Array();
    for (var i = 0; i < this.data.list.length; i++) {
      itemListTemp.push(this.data.list[i].listName);
    }
    this.setData({
      listName: itemListTemp,
      hiddenmodalput: false
    })
  },
  cancelM: function (e) {
    this.setData({
      hiddenmodalput: true,
    })
  },

  confirmM: function (e) {
    var listTemp = new Array();
    listTemp = this.data.list;
    var listAdd = {
      listName: this.data.createPlan,
      item: []
    };

    listTemp.push(listAdd);
    // hideBottomInput(this);
    wx.setStorageSync("list", this.data.list);
    setListItemCount(this);

    this.setData({
      list: listTemp,
      hiddenmodalput: true,
      createPlan: "",
      searchinput: ""
    })

    let Index = listTemp.length - 1, //获取点击的下标值 
      list = this.data.list;
    console.log(Index);
    cuSelectNum = Index;

    list[Index].show = !list[Index].show || false; //变换其打开、关闭的状态
    if (list[Index].show) { //如果点击后是展开状态，则让其他已经展开的列表变为收起状态 
      this.packUp(list, Index);
    }
    this.setData({
      buttonText: list[Index].listName,
      list,
      hiddenmodalput: true
    })
  },

  iName: function (e) {
    this.setData({
      createPlan: e.detail.value
    })
  },
  //选中某一个计划
  planClick: function (e) {
    /**
     * 点击下方选择了以及栏目之后展开相应栏目
     */
    let Index = e.currentTarget.dataset.parentindex, //获取点击的下标值 
      list = this.data.list;

    if (cuSelectNum != Index) {
      cuSelectNum = Index;

      list[Index].show = !list[Index].show || false; //变换其打开、关闭的状态
      if (list[Index].show) { //如果点击后是展开状态，则让其他已经展开的列表变为收起状态 
        this.packUp(list, Index);
      }
      // hideBottomInput(this);

      this.setData({
        buttonText: list[Index].listName,
        list,
        hiddenmodalput: true
      })
    } else {
      // hideBottomInput(this);
      this.setData({
        hiddenmodalput: true
      })
    }
  },
  data: {
    openid: "",
    session_key: "",
    isScope: false,
    isPlayScale: "",
    touch_start: 0,
    touch_end: 0,
    checkBg: "#fff",
    isBlur: false,
    showModalStatus: false,
    isInputShow: "none",
    itemOpacity: 0,
    animationData: {},
    transform: {},
    searchinput: "",
    createPlan: "",
    hiddenmodalput: true,
    listName: [],
    isFinsh: false,
    intputValue: "",
    buttonText: "默认计划",
    list: wx.getStorageSync("list"),
    // [{
    //   listName: '默认计划',
    //   item: [{
    //     itemName: 'a-1',
    //     content: '1-1中的内容',
    //     time: '2015-05-06',
    //     isChecked: false
    //   }, {
    //     itemName: 'a-2',
    //     content: '1-2中的内容',
    //     time: '2015-04-13'
    //   }, {
    //     itemName: 'a-3',
    //     content: '1-3中的内容',
    //     time: '2015-12-06',
    //     isChecked: false
    //   }]
    // }, {
    //   listName: '第二计划',
    //   item: [{
    //     itemName: 'a-1',
    //     content: '1-1中的内容',
    //     time: '2015-05-06',
    //     isChecked: false
    //   }, {
    //     itemName: 'a-2',
    //     content: '1-2中的内容',
    //     time: '2015-04-13',
    //     isChecked: false
    //   }, {
    //     itemName: 'a-3',
    //     content: '1-3中的内容',
    //     time: '2015-12-06',
    //     isChecked: false
    //   }]
    // }]
  }, //点击最外层列表展开收起 
  listTap(e) {
    // console.log('触发了最外层');
    let Index = e.currentTarget.dataset.parentindex, //获取点击的下标值 
      list = this.data.list;
    list[Index].show = !list[Index].show || false; //变换其打开、关闭的状态
    if (list[Index].show) { //如果点击后是展开状态，则让其他已经展开的列表变为收起状态 
      this.packUp(list, Index);
    }
    cuSelectNum = Index;

    this.setData({
      buttonText: list[Index].listName,
      list
    });
  }, //点击里面的子列表展开收起
  listItemTap(e) {
    //zzp
    let parentindex = e.currentTarget.dataset.parentindex, //点击的内层所在的最外层列表下标 
      Index = e.currentTarget.dataset.index, //点击的内层下标 
      list = this.data.list;
    // console.log(list[parentindex].item, Index);
    list[parentindex].item[Index].show = !list[parentindex].item[Index].show || false; //变换其打开、关闭的状态 
    if (list[parentindex].item[Index].show) { //如果是操作的打开状态，那么就让同级的其他列表变为关闭状态，保持始终只有一个打开 
      for (let i = 0, len = list[parentindex].item.length; i < len; i++) {
        if (i != Index) {
          list[parentindex].item[i].show = false;
        }
      }
    }
    this.setData({
      list
    });
  }, //让所有的展开项，都变为收起 
  packUp(data, index) {
    for (let i = 0, len = data.length; i < len; i++) { //其他最外层列表变为关闭状态
      if (index != i) {
        data[i].show = false;
        for (let j = 0; j < data[i].item.length; j++) { //其他所有内层也为关闭状态
          data[i].item[j].show = false;
        }
      }
    }
  },
  onLoad: function (options) {
    var obj = this;

    if (getApp().globalData.isOnline) {
      wx.login({
        success: function (e) {
          var code = e.code;
          wx.request({
            url: getApp().globalData.url + '/loginMain/getUserInfo',
            data: { js_code: code },
            method: 'POST',
            header: {
              // 'Content-Type': 'application/json'
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (e) {
              wx.setStorageSync("userId", e.data);

              wx.getNetworkType({
                success: function (res) {
                  // 返回网络类型, 有效值：
                  // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
                  var networkType = res.networkType
                  if (res.networkType != "none") {
                    doHttp(obj);
                  }
                }
              })

              obj.setData({
                isScope: true
              })
            }
          })
        },
        fail: function (e) {

        }
      })

    }


    if (wx.getStorageSync("list") == null || wx.getStorageSync("list") == "") {
      this.setData({
        list: [{
          listName: '默认计划',
          count: '(0/0)',
          item: []
        }]
      })
    }
    //zzp_1
    setTitle(this);
    setListItemCount(this);

    // console.log('触发了最外层');
    let Index = 0, //获取点击的下标值 
      list = this.data.list;
    list[Index].show = !list[Index].show || false; //变换其打开、关闭的状态
    if (list[Index].show) { //如果点击后是展开状态，则让其他已经展开的列表变为收起状态 
      this.packUp(list, Index);
    }
    list[0].show = true;
    cuSelectNum = Index;

    this.setData({
      buttonText: list[Index].listName,
      list
    });

  },
  /** * 生命周期函数--监听页面初次渲染完成 */
  onReady: function () { },
  /** * 生命周期函数--监听页面显示 */
  onShow: function () {

  },
  /** * 生命周期函数--监听页面隐藏 */
  onHide: function () { },
  /** * 生命周期函数--监听页面卸载 */
  onUnload: function () { },
  /** * 页面相关事件处理函数--监听用户下拉动作 */
  onPullDownRefresh: function () { },
  /** * 页面上拉触底事件的处理函数 */
  onReachBottom: function () { },
  /** * 用户点击右上角分享 */
  onShareAppMessage: function () { },
  //获取底部文本框的值
  inputText: function (e) {
    this.setData({
      intputValue: e.detail.value
    })
  },
  checkboxChange: function (e) {
    var isChecked = e.target.dataset.checks ? false : true;
    // console.log(isChecked);

    var index = parseInt(e.currentTarget.dataset.index);
    if (this.data.list[cuSelectNum].item[index].isChecked) {
      this.data.list[cuSelectNum].item[index].isChecked = false;
    } else {
      this.data.list[cuSelectNum].item[index].isChecked = true;
    }
    /**排序 start */
    var itemTemp = new Array();
    for (var i = 0; i < this.data.list[cuSelectNum].item.length; i++) {
      if (!this.data.list[cuSelectNum].item[i].isChecked) {
        itemTemp.push(this.data.list[cuSelectNum].item[i]);

      }
    }

    for (var i = 0; i < this.data.list[cuSelectNum].item.length; i++) {
      if (this.data.list[cuSelectNum].item[i].isChecked) {
        itemTemp.push(this.data.list[cuSelectNum].item[i]);
      }
    }

    this.data.list[cuSelectNum].item = itemTemp;

    this.setData({
      list: this.data.list
    })
    /**排序 end */
    wx.setStorageSync("list", this.data.list);
    //zzp_1
    setTitle(this);
    setListItemCount(this);
  },
  send: function (e) {
    var obj = this;
    if (this.data.intputValue != "") {
      var listTemp = new Array();
      listTemp = obj.data.list;
      var itemTemp = new Array();
      obj.data.list[cuSelectNum].item = [{
        itemName: obj.data.intputValue,
        content: '1-1中的内容',
        time: '2015-05-06',
        isChecked: false
      }].concat(obj.data.list[cuSelectNum].item);

      if (!obj.data.list[cuSelectNum].show) {
        obj.data.list[cuSelectNum].show = true;
      }
      wx.setStorageSync("list", obj.data.list);
      setListItemCount(obj);
      playTextAnim(obj);

      setTitle(obj);
      hideBottomInput(obj);

      if (getApp().globalData.isOnline) {
        sendData(obj);
      }
    } else {
      wx.showModal({
        content: '请输入字符',
        showCancel: false, //不显示取消按钮
        confirmText: '确定'
      })
    }
  },
  showModal: function () {
    showBottomInput(this);
  },
  hideModal: function () {
    hideBottomInput(this)
  },
  checkboxTouchStart: function (e) {
    let that = this;
    that.setData({
      touch_start: e.timeStamp
    })
  },
  checkboxTouchEnd: function (e) {
    let that = this;
    that.setData({
      touch_end: e.timeStamp
    })
  },
  checkboxLongClick: function (e) {
    var clickNum = e.currentTarget.dataset.index;
    var obj = this;

    wx.showModal({
      title: '提示',
      content: '确定要删除' + this.data.list[cuSelectNum].item[clickNum].itemName + "吗？",
      success: function (res) {
        if (res.confirm) {
          //确定          
          setListItemCount(obj);
          obj.data.list[cuSelectNum].item.splice(clickNum, 1);
          setListItemCount(obj);
          obj.setData({
            list: obj.data.list
          })
        } else if (res.cancel) {
          //取消
        }
      }
    })
  },
  listLongClick: function (e) {
    var clickNum = e.currentTarget.dataset.index;
    var obj = this;
    console.log(clickNum);
    wx.showModal({
      title: '提示',
      content: '确定要删除' + this.data.list[clickNum].listName + "吗？",
      success: function (res) {
        if (res.confirm) {
          //确定          
          setListItemCount(obj);
          obj.data.list.splice(clickNum, 1);
          obj.setData({
            list: obj.data.list
          })
        } else if (res.cancel) {
          //取消
        }
      }
    })
  }
})